import { getBaseUrl } from '@/utils/env';
import { getCache } from '@/utils/cache';
import { TOKEN_KEY } from '@/enums/cacheEnum';
// import { useAuthStore } from '@/store/modules/auth';
// const authStore = useAuthStore();
console.log(process.env.NODE_ENV);

const baseUrl = getBaseUrl();

const CONTENT_TYPE = {
    JSON: 'application/json;charset=UTF-8',
    FORM_URLENCODED: 'application/x-www-form-urlencoded;charset=UTF-8',
    FORM_DATA: 'multipart/form-data;charset=UTF-8',
};

export interface requestType {
    code: number;
    data?: any;
    message: string;
    status: boolean;
}
type ServeType = 'AUTH' | 'PROPERTY' | 'FILE' | 'JOB' | 'BPM';

type HttpMethod = 'POST' | 'OPTIONS' | 'GET' | 'HEAD' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT';
type ContentType = 'JSON' | 'FORM_URLENCODED';
const DEFAULT_SERVE: ServeType = 'AUTH';
const DEFAULT_METHOD: HttpMethod = 'GET';
const DEFAULT_CONTENT_TYPE: ContentType = 'JSON';

interface Request {
    serve?: ServeType;
    url: string;
    method: HttpMethod;
    body?: any;
    hideLoading?: boolean;
    contentType?: ContentType;
    headers?: any;
    timeout?: number;
}
const request = async ({
    serve = DEFAULT_SERVE,
    url = '',
    method = DEFAULT_METHOD,
    body = {},
    hideLoading = true, //是否显示请求loading
    contentType = DEFAULT_CONTENT_TYPE,
    headers = {},
    timeout = 6000,
}: Request): Promise<requestType> => {
    if (!hideLoading) {
        uni.showLoading({
            mask: true,
        });
    }
    url = baseUrl + url;
    const requestUrl = url;
    const token = getCache(TOKEN_KEY);
    const authHeaders = {
        Authorization: token ? `Bearer ${token}` : '',
        Cookie: token ? `Bearer ${token}` : '',
        terminal: 10,
    };
    try {
        const res: any = await uni.request({
            url: requestUrl,
            method: method,
            data: body,
            header: Object.assign(authHeaders, headers),
            timeout,
            enableCache: true, // 自动处理缓存
        });

        const { data }: any = res;

        if (res.data.code === 401) {
            //需要重新登录清除store
            // userStore().$reset()
            uni.reLaunch({
                url: '/pages/login/index',
            });
            return Promise.reject('需要重新登录');
        }

        if (res.statusCode !== 200) {
            uni.showToast({
                icon: 'none',
                title: '系统错误',
            });
            return Promise.reject('系统错误');
        }

        if (res.data.code === 0) {
            return Promise.resolve(data);
        }
		if (res.data.code === 1004013004) {
		    uni.navigateTo({
		        url: '/pages/settled/index',
		    });
		    return Promise.reject('该用户未申请医生资质');
		}
		if (res.data.code === 1004003001) {
			uni.showToast({
			    icon: 'none',
			    title: '用户申请被拒绝，请重新申请',
			});
		    setTimeout(()=>{
					uni.navigateTo({
					    url: '/pages/settled/index',
					});
				},1000)
		    return Promise.reject('用户申请被拒绝，请重新申请');
		}
		
        uni.showToast({
            icon: 'none',
            title: res.data.msg,
        });
        //异常抛出
        return Promise.reject(res.data.msg);
    } catch (error) {
        return Promise.reject('请求失败');
    } finally {
        if (!hideLoading) {
            uni.hideLoading({
                noConflict: true, //解决微信小程序Loading 和 showToast无法共用
            });
        }
    }
};
export default request;
